package com.zf.zfed.audit.ui

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import androidx.core.content.ContextCompat
import com.zf.zfed.audit.R
import com.zf.zfed.audit.tools.extension.dpFromDimen
import kotlin.math.max
import kotlin.math.min

/**
 * 自定义亮度滑动条控件
 * 支持左右滑动调节屏幕亮度，左侧亮度变暗，右侧亮度变亮
 */
class BrightnessSlider @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    // 滑动条相关属性
    private var progress = 50f // 当前进度 0-100
    private var maxProgress = 100f
    private var minProgress = 0f
    
    // 绘制相关
    private var trackPaint = Paint(Paint.ANTI_ALIAS_FLAG)
    private var progressPaint = Paint(Paint.ANTI_ALIAS_FLAG)
    private var thumbPaint = Paint(Paint.ANTI_ALIAS_FLAG)
    private var borderPaint = Paint(Paint.ANTI_ALIAS_FLAG)
    
    // 尺寸相关
    private var trackHeight = 0f
    private var thumbRadius = 0f
    private var trackStartX = 0f
    private var trackEndX = 0f
    private var trackCenterY = 0f
    
    // 触摸相关
    private var isDragging = false
    private var lastTouchX = 0f
    
    // 监听器
    private var onBrightnessChangeListener: OnBrightnessChangeListener? = null
    
    init {
        initPaint()
        initDimensions()
        
        // 处理自定义属性
        if (attrs != null) {
            val typedArray = context.obtainStyledAttributes(attrs, R.styleable.BrightnessSlider)
            progress = typedArray.getFloat(R.styleable.BrightnessSlider_brightness_progress, 50f)
            maxProgress = typedArray.getFloat(R.styleable.BrightnessSlider_brightness_max, 100f)
            minProgress = typedArray.getFloat(R.styleable.BrightnessSlider_brightness_min, 0f)
            typedArray.recycle()
        }
    }
    
    private fun initPaint() {
        // 轨道画笔 - 使用白色作为未激活部分
        trackPaint.apply {
            color = ContextCompat.getColor(context, R.color.slider_inactive)
            style = Paint.Style.FILL
        }
        
        // 进度画笔 - 使用蓝色表示激活部分
        progressPaint.apply {
            color = ContextCompat.getColor(context, R.color.slider_active)
            style = Paint.Style.FILL
        }
        
        // 滑块画笔 - 使用白色
        thumbPaint.apply {
            color = ContextCompat.getColor(context, R.color.slider_thumb)
            style = Paint.Style.FILL
            setShadowLayer(4f, 0f, 2f, Color.argb(50, 0, 0, 0))
        }
        
        // 边框画笔 - 使用蓝色边框
        borderPaint.apply {
            color = ContextCompat.getColor(context, R.color.slider_active)
            style = Paint.Style.STROKE
            strokeWidth = context.dpFromDimen(R.dimen.size_1).toFloat()
        }
    }
    
    private fun initDimensions() {
        trackHeight = context.dpFromDimen(R.dimen.size_10).toFloat()
        thumbRadius = context.dpFromDimen(R.dimen.size_9).toFloat()
    }
    
    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        
//        val paddingHorizontal = context.dpFromDimen(R.dimen.spacing_2).toFloat()
        val paddingHorizontal = context.dpFromDimen(R.dimen.spacing_10).toFloat()
        trackStartX = paddingHorizontal+ thumbRadius
        trackEndX = w.toFloat() -  thumbRadius
        trackCenterY = h / 2f
    }
    
    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        
        drawTrack(canvas)
        drawProgress(canvas)
        drawThumb(canvas)
    }
    
    private fun drawTrack(canvas: Canvas) {
        val trackTop = trackCenterY - trackHeight / 2
        val trackBottom = trackCenterY + trackHeight / 2
        val trackRect = RectF(trackStartX, trackTop, trackEndX, trackBottom)
        canvas.drawRoundRect(trackRect, trackHeight / 2, trackHeight / 2, trackPaint)
        
        // 绘制蓝色边框
        canvas.drawRoundRect(trackRect, trackHeight / 2, trackHeight / 2, borderPaint)
    }
    
    private fun drawProgress(canvas: Canvas) {
        val progressWidth = (trackEndX - trackStartX) * (progress / maxProgress)
        val progressRight = trackStartX + progressWidth
        
        val trackTop = trackCenterY - trackHeight / 2
        val trackBottom = trackCenterY + trackHeight / 2
        val progressRect = RectF(trackStartX, trackTop, progressRight, trackBottom)
        canvas.drawRoundRect(progressRect, trackHeight / 2, trackHeight / 2, progressPaint)
    }
    
    private fun drawThumb(canvas: Canvas) {
        val thumbX = trackStartX + (trackEndX - trackStartX) * (progress / maxProgress)
        canvas.drawCircle(thumbX, trackCenterY, thumbRadius, thumbPaint)
    }
    
    @SuppressLint("ClickableViewAccessibility")
    override fun onTouchEvent(event: MotionEvent): Boolean {
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                lastTouchX = event.x
                isDragging = true
                parent.requestDisallowInterceptTouchEvent(true)
                return true
            }
            
            MotionEvent.ACTION_MOVE -> {
                if (isDragging) {
                    updateProgress(event.x)
                    invalidate()
                }
                return true
            }
            
            MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                isDragging = false
                parent.requestDisallowInterceptTouchEvent(false)
                return true
            }
        }
        return super.onTouchEvent(event)
    }
    
    private fun updateProgress(touchX: Float) {
        val trackWidth = trackEndX - trackStartX
        val relativeX = touchX - trackStartX
        val newProgress = (relativeX / trackWidth) * maxProgress
        
        setProgress(newProgress)
    }
    
    /**
     * 设置进度值
     */
    fun setProgress(newProgress: Float) {
        val clampedProgress = max(minProgress, min(maxProgress, newProgress))
        if (progress != clampedProgress) {
            progress = clampedProgress
            onBrightnessChangeListener?.onBrightnessChanged(progress)
            invalidate()
        }
    }
    
    /**
     * 获取当前进度值
     */
    fun getProgress(): Float = progress
    
    /**
     * 设置亮度变化监听器
     */
    fun setOnBrightnessChangeListener(listener: OnBrightnessChangeListener) {
        onBrightnessChangeListener = listener
    }
    
    /**
     * 亮度变化监听器接口
     */
    interface OnBrightnessChangeListener {
        fun onBrightnessChanged(brightness: Float)
    }
    
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        val desiredHeight = context.dpFromDimen(R.dimen.size_48)
        val height = resolveSize(desiredHeight, heightMeasureSpec)
        val width = MeasureSpec.getSize(widthMeasureSpec)
        setMeasuredDimension(width, height)
    }
}